package com.gitee.dupe.authority.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.gitee.dolt.annotation.security.PreAuth;
import com.gitee.dolt.boot.controller.SuperCacheController;
import com.gitee.dolt.boot.request.QueryParams;
import com.gitee.dolt.core.base.Result;
import com.gitee.dupe.authority.entity.Resource;
import com.gitee.dupe.authority.extend.AuthorityCustomOperate;
import com.gitee.dupe.authority.service.IResourceService;
import com.gitee.dupe.authority.service.impl.ResourceServiceImpl;
import io.swagger.annotations.Api;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author LYH
 * @since 2020-06-30
 */
@RestController
@RequestMapping("/b/resource")
@Validated
@Api(value = "Resource", tags = "资源")
@RequiredArgsConstructor
@PreAuth(replace = "b:resource:")
public class ResourceController extends SuperCacheController<Resource, IResourceService, Long, Resource, Resource, Resource> {

    private final AuthorityCustomOperate authorityCustomOperate;

    @Override
    public QueryWrapper<Resource> handlerQueryWrapper(Resource resource, QueryParams<Resource> params) {
        QueryWrapper<Resource> qw = Wrappers.query();
        String keyword = params.getKeyword();
        if (StrUtil.isNotEmpty(keyword)) {
            if (authorityCustomOperate.resourceQueryWithParent()) {
                qw.and(e -> e.like("a.ident", keyword).or().like("a.name", keyword));
            } else {
                qw.lambda().and(e -> e.like(Resource::getIdent, keyword).or().like(Resource::getName, keyword));
            }
        }
        return qw;
    }

    @Override
    public boolean enableQuery() {
        return true;
    }

////     用于缓存测试
//    @GetMapping("/getByIdent")
//    public Result getByIdent(String ident) {
//        Object oo = ((ResourceServiceImpl) baseService).getCacheManager("OO").getByKey(ident, e -> baseService.getOne(Wrappers.<Resource>
//                lambdaQuery().eq(Resource::getIdent, ident)));
//        return Result.ok(oo);
//    }
}
